package demo9

// 享元设计模式
import "fmt"
// 重复的运用同一个实例化对象避免重复的开辟空间来使用

// 管理所有的对象
type ImageFlyweightFactory struct{
	maps map[string]*ImageFlyweight
}

var imageFactory *ImageFlyweightFactory

// 构造函数
func GetImageFlyweightFactory() *ImageFlyweightFactory{
	if imageFactory == nil {
		imageFactory = &ImageFlyweightFactory{
			maps:make(map[string]*ImageFlyweight),
		}
	}
	return imageFactory
}
// 获取实例化某个对象 有点类似服务注册
func (f *ImageFlyweightFactory)Get(filename string) *ImageFlyweight{
	image := f.maps[filename]
	if image == nil {
		image = NewImageFlyweight(filename)
		f.maps[filename] = image
	}
	return image
}

// 实例化对象
type ImageFlyweight struct{
	data string
}

// 生成对象
func NewImageFlyweight(filename string) *ImageFlyweight{
	data := fmt.Sprintf("image data %s",filename)
	return &ImageFlyweight{
		data:data,
	}
}

func (i *ImageFlyweight) Data()string{
	return i.data
}

// 储存结果
type ImageViewer struct{
	*ImageFlyweight
}

func NewImageViewer(filename string) *ImageViewer{
	image := GetImageFlyweightFactory().Get(filename)
	return &ImageViewer{
		ImageFlyweight:image,
	}
}

func (i *ImageViewer) Display(){
	fmt.Println("Display:",i.Data())
}